import hypermedia.video.OpenCV;
import java.awt.*;
import java.awt.image.MemoryImageSource;
import hypermedia.video.*;

public class ViewPanel extends Panel implements Runnable{
    private OpenCV cv = null;
    private Image img = null;
    private Blob[] blobs = null;
    private Thread t = null;
    final float THRESHOLD = 160f; //Adjust this as needed
        
    public ViewPanel() {
            super();
            t = new Thread( this );
    }

    @Override
    public void paint(Graphics g){
        
        if (this.img != null){
            g.drawImage(img, 0, 0, this);
            
            for( Blob b : blobs ) {
                // define blob's contour
                Polygon shape = new Polygon();
                for( Point p : b.points ) shape.addPoint( p.x, p.y );
                
                g.setColor( b.isHole ? Color.RED : Color.BLUE );
                g.fillPolygon( shape );
            }
        }
    }

    @Override
    public void run() {
        cv = new OpenCV();
        cv.capture( 320, 240 );
        cv.cascade( OpenCV.CASCADE_FRONTALFACE_ALT );
        
        while( t!=null && cv!=null ) {
            
            cv.read();
            cv.flip( OpenCV.FLIP_HORIZONTAL );
            
            MemoryImageSource mis = new MemoryImageSource( cv.width, cv.height, cv.pixels(), 0, cv.width );
            img = createImage( mis );
            
            cv.absDiff();
            cv.threshold( THRESHOLD );
            
            blobs = cv.blobs( 30, cv.width*(cv.height/2), 100, true, OpenCV.MAX_VERTICES*4 );
            
            repaint();
        }
        
    }
    
    public void stop() {
        t = null;
        cv.dispose();
    }
    public void start() {
        this.t.start();
    }
    
}